package club.janna.hello.dao;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import club.janna.hello.model.ChannelModel;
import org.apache.commons.lang.StringUtils;

/**
 * 内存通道访问对象
 */
public class MemoryChannelDao extends AbstractChannelDao {

	private MemoryChannelDao() {}

	private static class MemoryChannelDaoFactory {
		private static MemoryChannelDao instance = new MemoryChannelDao();
	}

	public static MemoryChannelDao getInstance() {
		return MemoryChannelDaoFactory.instance;
	}

	private Map<String, ChannelModel> data = new HashMap<>();
	
	@Override
	public void delete(ChannelModel channel) {
		// TODO Auto-generated method stub
		if(channel == null || StringUtils.isEmpty(channel.getId()))
			throw new RuntimeException("channel is null, delete faild");
		data.remove(channel.getId());
	}

	@Override
	public Collection<ChannelModel> getActiveChannels() {
		// TODO Auto-generated method stub
		return data.values();
	}

	@Override
	public void update(ChannelModel channel) {
		// TODO Auto-generated method stub
		doCreate(channel);
	}

	@Override
	public String doCreate(ChannelModel channel) {
		// TODO Auto-generated method stub
		if(channel == null || StringUtils.isEmpty(channel.getId()) || channel.getChannel() == null)
			throw new RuntimeException("channel is null, create faild");
		ChannelModel cur = data.get(channel.getId());
		Date curTime = new Date();
		if(cur == null) {
			channel.setCreateTime(curTime);
			data.put(channel.getId(), channel);
		} else {
			if(channel.getChannel() == cur.getChannel())
				cur.setUpdateTime(curTime);
			else {
				channel.setCreateTime(curTime);
				data.put(channel.getId(), channel);
			}
		}
		return channel.getId();
	}

	@Override
	public ChannelModel doReadChannel(String id) {
		// TODO Auto-generated method stub
		if(StringUtils.isEmpty(id))
			return null;
		return data.get(id);
	}

}
